package com.fingard.dsp.bank.directbank.ceb02;

import java.io.UnsupportedEncodingException;
import java.util.Date;


import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.allinpay.ets.client.StringUtil;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.ceb02.bankUtil.HttpHelper;
import com.fingard.dsp.bank.directbank.ceb02.bankUtil.MacUtil;
import com.fingard.dsp.bank.directbank.ceb02.bankUtil.ReadContentToTxt;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CEB02Base extends DirectBase {
	protected static TransIDHelper idHelper = new TransIDHelper(1,9999);
	
	/**光大第三批报文结构风格*/
	protected void writeCommonHeader_3(XmlTextWriter xmlWriter, CEB02Header p_bankHeader) throws Exception{
		
		if(StringHelper.isNullOrEmpty(p_bankHeader.FTranCode))
		{
			throw new Exception("未赋值交易码FTranCode");
		}
				
						
		//报文前六位加上报文长度
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
		xmlWriter.writeStartElement("In");
		
		xmlWriter.writeStartElement("Head");
		xmlWriter.writeElementString("ChnlNo", bankFront.corpNo);//渠道号
		xmlWriter.writeElementString("FTranCode",p_bankHeader.FTranCode);//交易码
		xmlWriter.writeElementString("InstID",bankFront.org);//机构号
		xmlWriter.writeElementString("TrmSeqNum",getTrmSeqNum());//终端流水号
		xmlWriter.writeElementString("TranDateTime",Format.DateTime14Format.format(new Date()));//交易日期YYYYMMDDhhmmss
		xmlWriter.writeElementString("ErrCode","");//错误码
		xmlWriter.writeEndElement();
		
	}
	
	protected String getBatchID(){
		return Format.DateTime12Year2Format.format(new Date())+idHelper.getNextIDStr();
	}
	
	protected String getCharset() {
        return getBankConfig().getCharset("GB18030");
    }
	
	protected String[] sendToBank(String p_reqStr,CEB02Header p_bankHeader) throws Exception{

        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        WriteBankLogStep2(p_reqStr);
        //获取mac
        String[] key = sendToBankForMac(p_bankHeader);
        if(key[0].isEmpty()) {
        	WriteBankLogLn("获取MAC值失败");
        	return retStr;
        }
        String mac = MacUtil.updateKey(p_reqStr,key);
		String p_reqStr_l = p_reqStr + mac;
        int length = p_reqStr_l.getBytes(getCharset()).length;
        //在上送报文前添加报文长度6位数字
        String p_reqStrz = String.format("%06d",length)+p_reqStr_l;
        //发送银行前置
        String charsetName = "GBK";
        byte[] tmpUpBytes = p_reqStrz.getBytes(charsetName);
        //retStr = tmpWebRequest.upload(tmpUpBytes, charsetName);
       // HttpHelper client= new HttpHelper();
		//retStr = client.post(tmpUpBytes, bankFront.serverURL);
		WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        String[] tmpStrRet = tmpWebRequest.upload(tmpUpBytes, charsetName);
        WriteBankLogStep3(tmpStrRet[1]);
        
        //报文去头去尾
        if(tmpStrRet[1].length()>16) {
        	tmpStrRet[1] = tmpStrRet[1].substring(6, tmpStrRet[1].length()-16);
        }
        
        return tmpStrRet;
    }
    
    protected String getTrmSeqNum() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }
    
    //获取密钥和校验值
    protected String[] sendToBankForMac(CEB02Header p_bankHeader) throws Exception {
    	String[] args = {"",""};
    	//检查是否需要更新mac
    	String mac = ReadContentToTxt.getString();
    	if(mac != null && mac.length()==3) {
    		mac = null;
    	}
    	if(mac != null && mac.length()>0) {
    		args[0] = mac.split(",")[0];
    		args[1] = mac.split(",")[1];
    		if (args[1]!=null) {
    			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
    			Matcher m = p.matcher(args[1]);
    			args[1] = m.replaceAll("");
    		}
    		return args;
    	}
    	
    	//构造请求报文
    	XmlTextWriter xmlWriter = new XmlTextWriter();
    	xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
		xmlWriter.writeStartElement("In");
		
		xmlWriter.writeStartElement("Head");
		xmlWriter.writeElementString("ChnlNo", bankFront.corpNo);//渠道号
		xmlWriter.writeElementString("FTranCode","9000");//交易码
		xmlWriter.writeElementString("InstID",bankFront.org);//机构号
		xmlWriter.writeElementString("TrmSeqNum",getTrmSeqNum());//终端流水号
		xmlWriter.writeElementString("TranDateTime",Format.DateTime14Format.format(new Date()));//交易日期
		xmlWriter.writeElementString("ErrCode", "");//错误码
		xmlWriter.writeEndElement();
		xmlWriter.writeStartElement("Body");
		xmlWriter.writeElementString("operationDate",Format.Date8Format.format(new Date()));
		xmlWriter.writeEndElement();
		xmlWriter.writeEndDocument();
		int length = xmlWriter.toXmlString().getBytes(getCharset()).length;
		String toXml = String.format("%06d",length)+xmlWriter.toXmlString();
        String charsetName = "GBK";
        byte[] tmpUpBytes = null;
		try {
			tmpUpBytes = toXml.getBytes(charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		HttpHelper client= new HttpHelper();
		//String[] tmpStrRet = client.post(tmpUpBytes, bankFront.serverURL);
		WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        String[] tmpStrRet = tmpWebRequest.upload(tmpUpBytes, charsetName);
        
        if(tmpStrRet[0].length() == 0){
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if(tmpBkReader != null){
            	
                while (tmpBkReader.read("/Out/Body")){
                    String macKeyValue = tmpBkReader.readedXElement.getSingleTextNotNull("macKeyValue");
                    String macVerifyValue = tmpBkReader.readedXElement.getSingleTextNotNull("macVerifyValue");
                    if (!StringHelper.isNullOrEmpty(macKeyValue)) {
                    	    args[0] = macKeyValue;
                    	    args[1] = macVerifyValue;
                    } 
                }
            } 
        
        }
        //更新密钥文件（当天重复使用）
        ReadContentToTxt.setString(args);
        return args;
    }
    //上送格式为json格式
    protected String[] sendToATS(String jsonData) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        //发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(10000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String charsetName = getCharset();
        StringBuilder data = new StringBuilder();
        data.append(jsonData);
        WriteBankLogLn("3.推送给ATS的数据" + data.toString());
        byte[] tmpWriteBytes = data.toString().getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据" + retStr[1]);

        return retStr;
    }
    
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
    	         int n = gbkStr.length();  
    	         byte[] utfBytes = new byte[3 * n];  
    	         int k = 0;  
    	        for (int i = 0; i < n; i++) {  
    	            int m = gbkStr.charAt(i);  
    	             if (m < 128 && m >= 0) {  
    	                utfBytes[k++] = (byte) m;  
    	                 continue;  
    	             }  
    	             utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
    	             utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
    	             utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
    	         }  
    	         if (k < utfBytes.length) {  
    	             byte[] tmp = new byte[k];  
    	             System.arraycopy(utfBytes, 0, tmp, 0, k);  
    	             return tmp;  
    	         }  
    	         return utfBytes;  
    	     }  
}
